/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
 *
 */

import path from 'path';

import { CommonConst } from '../../const/common-const.js';
import { DeviceTypeConst } from '../../const/device-type-const';
import { ConfigJson } from '../../options/configure/config-json-options.js';
import { ShellUtils } from '../../utils/shell-utils';

import { CoreResModelImpl } from './core-res-model-impl.js';
import ConfigOptObj = ConfigJson.ConfigOptObj;
import { BuildDirConst } from '../../const/build-directory-const.js';
import { resModelLoader } from '../../utils/loader/file/res-model-loader.js';
import { OhosLogger } from '../../utils/log/ohos-logger.js';

import { LegacyModuleTargetRes } from './res-model.js';

/**
 * Fa Module 的不同target对应的资源集合
 *
 * @since 2022/2/23
 */
export class LegacyModuleTargetResImpl extends CoreResModelImpl implements LegacyModuleTargetRes {
  protected _configJsonOpt: ConfigOptObj | undefined;
  private _log = OhosLogger.getLogger('LegacyModuleTargetResImpl');

  constructor(sourceSetRoot: string) {
    super(path.resolve(sourceSetRoot, CommonConst.CONFIG_JSON), path.resolve(sourceSetRoot, BuildDirConst.RESTOOL_BUILD_RESOURCES));
  }

  getConfigJsonOpt(): ConfigOptObj {
    if (!this._configJsonOpt) {
      this._configJsonOpt = resModelLoader.getConfigJson(this.getJsonPath());
      if (!this._configJsonOpt) {
        return this._configJsonOpt!;
      }
      const abilities = this._configJsonOpt?.module?.abilities;
      if (this.hasLiteDevice() && abilities && abilities.length > 0) {
        this._configJsonOpt.module.mainAbility = abilities[0].name;
      }
    }
    return this._configJsonOpt!;
  }

  public hasLiteDevice(): boolean | undefined {
    if (!this._configJsonOpt) {
      throw new Error(`${this.getJsonPath()} content is not obtained.`);
    }
    if (!this._configJsonOpt.module.deviceType) {
      return true;
    }
    return this._configJsonOpt.module.deviceType.some((deviceType) => {
      return deviceType === 'liteWearable' || deviceType === 'smartVision';
    });
  }

  supportLiteDeviceModule(): boolean {
    const deviceTypes = this.getConfigJsonOpt().module.deviceType;
    return deviceTypes && (deviceTypes.includes(DeviceTypeConst.LITE_WEARABLE) || deviceTypes.includes(DeviceTypeConst.SMART_VISION));
  }

  getShellApplicationPackage(): string {
    // 瘦设备混合模式使用固定ApplicationPackage
    if (this.supportLiteDeviceModule()) {
      return ShellUtils.JS_SHELL_APPLICATION_FULL;
    }
    const module = this.getConfigJsonOpt().module;
    if (!module.name) {
      this._log.error(`Check ${this.getJsonPath()} and make sure ` + 'the name field under the module tag is set correctly.');
    }
    return `${module.package}.Shell${module.name?.substring(module.name.lastIndexOf('.') + 1)}`;
  }
}
